<?php
include_once 'include.php';

$lid = $_POST['lid'];
$to = $_POST['to'];
$bid = $_POST['bid'];
$cid = $_POST['cid'];
$uid = $_POST['uid'];

$letters = new SetLetters();
$letters = $letters->find((int)$lid);

$ConfigObj = new GeneralConfig();
$config = $ConfigObj->find(1);

$UnitObj = new Unit();
$BookingObj = new Booking();
$CustomerObj = new Customer();

if($to == "GUEST"){
	$guest = $CustomerObj->select_row_query("SELECT `email` FROM `".$CustomerObj->get_table_name()."` WHERE `id` = '$cid'", 1);
	$to = $guest->email;
}
else if($to == "OWNER"){
	$owner = $CustomerObj->select_row_query("SELECT `email` FROM `".$CustomerObj->get_table_name()."` WHERE `id` = (SELECT `owner_id` FROM `".$UnitObj->get_table_name()."` WHERE `id` = '$bookings->uid')", 1);
	$to = $owner->email;
}

$count = $BookingObj->count("SELECT `id` FROM `".$BookingObj->get_table_name()."` WHERE `id` = $bid AND `uid` = $uid AND `cid` = $cid");
if($count > 0){
	$replacer = $ConfigObj->select_row_query("SELECT t1.id as booking_id, t1.startdate, t1.enddate, t1.total_price, t1.discount, t1.adults, t1.children, t1.notes, t2.name, t3.title as cust_title, t3.firstname, t3.surname, t2.local_phone_number, t2.villa_phone_number, t2.local_contact_name, t2.lockbox_code, t2.driving_direction FROM `".$BookingObj->get_table_name()."` as t1, `".$UnitObj->get_table_name()."` as t2, `".$CustomerObj->get_table_name()."` as t3 WHERE t1.id='$bid' AND t2.id='$uid' AND t3.id='$cid'", 1);
}
$subject = $letters->msg_subject;
$body = configure_set_letter($letters->msg_body, $replacer);

$message = '<html>
	<head>
	  <title>'.$subject.'</title>
	</head>
	<body>';
$message .= $body;
$message .= '</body></html>';

// The Content-type header, to send HTML mail 
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'From: '. $config->admin_email . "\r\n";

if( !filter_var($to, FILTER_VALIDATE_EMAIL) ){
	$send_to = $config->admin_email;
	$subject = "Re: ".$letters->msg_subject;
	$message = "A mail has been sent from Booking Reference: ".$bid.". The mail couldn't be delivered to the intended user as his/her mail id(".$to.") could not be verified. <br />Please ensure that the user has entered correct email information. This may also be caused if someone is trying to access your site illegaly.";
	$message .= "<br><br><b>Please do not reply to this mail.</b>";
	$headers .= "From: developer.bookman@no-reply.com\r\n";
}
else{
	$send_to = $to;
	$headers .= 'From: '. $config->admin_email . "\r\n";
	$headers .= 'Cc: '. $config->admin_email . "\r\n";
}

if( mail($send_to, $subject, $message, $headers) ) echo error_get_last();
else echo "error";
?>